/*
 * @Description:
 * @Version: 1.0
 * @Autor: ycb
 * @Date: 2022-03-23 11:07:02
 * @LastEditors: ycb
 * @LastEditTime: 2022-04-01 18:11:51
 */
package flv

import (
	"log"
	"net/http"
	"sync"
)

type FlvClient struct {
	// 用来传输二进制的
	FlvDataChan chan []byte
	// FLVCLient key的唯一id
	Key string
	// socket阻塞
	SocketWaitChan chan string
	// 把指针存起来
	HttpRes http.ResponseWriter
	// 刷新
	HttpFlush http.Flusher
	// 流地址
	URL_PATH string
	// http交互失效
	http_faild bool
	// 加个锁试试
	lock sync.Mutex
	// 退出
	quit bool
}

func (flv_client *FlvClient) SetFlvStream(stream []byte) bool {

	flv_client.lock.Lock()
	if flv_client.http_faild {
		log.Printf("数据发送过程中出现异常 %s 断开连接", flv_client.Key)
		flv_client.lock.Unlock()
		return false
	}
	flv_client.lock.Unlock()

	flv_client.FlvDataChan <- stream

	return true
}

func (flv_client *FlvClient) Close() {
	flv_client.quit = true
	flv_client.FlvDataChan <- []byte{}
}

func (flv_client *FlvClient) Start() {

	flv_client.http_faild = false
	flv_client.quit = false

	for bytes := range flv_client.FlvDataChan {
		if flv_client.quit {
			return
		}

		// if flv_client.first_send {
		// 	flv_client.first_send = false
		// 	// 第一次发送数据 构造一个空的buffer进行发送带着 第一帧的时间戳
		// 	pts_buffer := []byte{
		// 		0x08,
		// 		0x00, 0x00, 0x04,
		// 		bytes[4], bytes[5], bytes[6], bytes[7],
		// 		0x00, 0x00, 0x00,
		// 		0xaf, 0x00, 0x13, 0x10,
		// 		0x00, 0x00, 0x00, 0x0f,
		// 	}

		// 	if _, err := flv_client.HttpRes.Write(pts_buffer); err != nil {
		// 		flv_client.lock.Lock()
		// 		flv_client.http_faild = true
		// 		flv_client.lock.Unlock()
		// 	}

		// }

		if _, err := flv_client.HttpRes.Write(bytes); err != nil {
			flv_client.lock.Lock()
			flv_client.http_faild = true
			flv_client.lock.Unlock()
		}
		flv_client.HttpFlush.Flush()
	}
}
